"""
---------------------------------------------------------------------
- File: app_utils.py
- Date: 2025/8/9
- Author: yangzhide
- Email: xxzjyzd@126.com
- Description: 工具函数
---------------------------------------------------------------------
"""

import re
import time

from pydantic import BaseModel, ConfigDict


def camel_case_convert(data: dict):
    """
    将字典的键从下划线命名法（snake case）转换为小驼峰命名法（lower camel case）
    例：{"user_name": 1} => {"userName": 1}
    :param data:
    :return:
    """
    converted_data = {}
    for key, value in data.items():
        converted_key = "".join(
            word.capitalize() if i else word for i, word in enumerate(key.split("_"))
        )
        converted_data[converted_key] = value
        # converted_data[to_snake_case(key)] = value
    return converted_data


def snake_case_convert(data: dict):
    """
    将字典的键从小驼峰命名法（lower camel case）或其他格式转换为下划线命名法（snake case)
    例：{"userName": 1} => {"user_name": 1}
    :param data:
    :return:
    """
    converted_data = {}
    for key, value in data.items():
        converted_data[to_snake_case(key)] = value
    return converted_data


def to_snake_case(x):
    """
    将字符串从驼峰命名法（包括小驼峰和大驼峰）转换为下划线命名法
    例：userLoginCount => user_login_count
    :param x:
    :return:
    """
    return re.sub(r"(?<=[a-z])[A-Z]|(?<!^)[A-Z](?=[a-z])", "_\\g<0>", x).lower()


def to_camel_case(x):
    """
    将字符串从下划线命名法转换为小驼峰命名法（首字母小写）
    例：user_login_count => userLoginCount
    :param x:
    :return:
    """
    return re.sub("_([a-zA-Z])", lambda m: (m.group(1).upper()), x)


def to_upper_camel_case(x):
    """
    将字符串从下划线命名法转换为大驼峰命名法（首字母大写）
    例：user_login_count => UserLoginCount
    :param x:
    :return:
    """
    s = re.sub("_([a-zA-Z])", lambda m: (m.group(1).upper()), x)
    return s[0].upper() + s[1:]


def to_lower_camel_case(x):
    """
    将字符串从下划线命名法转换为小驼峰命名法（首字母小写）
    :param x:
    :return:
    """
    s = re.sub("_([a-zA-Z])", lambda m: (m.group(1).upper()), x)
    return s[0].lower() + s[1:]


def convert_keys_to_camel_case(data):
    """递归将字典或列表中的所有键转换为小驼峰命名"""
    if isinstance(data, dict):
        # 如果是字典，转换键并递归处理值
        return {
            to_lower_camel_case(k): convert_keys_to_camel_case(v)
            for k, v in data.items()
        }
    elif isinstance(data, list):
        # 如果是列表，递归处理每个元素
        return [convert_keys_to_camel_case(item) for item in data]
    else:
        # 如果是其他类型，直接返回
        return data


# ---时间转换---


def timestamp_to_time(timestamp):
    """时间戳转换为字符串固定格式"""
    time_struct = time.localtime(timestamp)
    time_string = time.strftime("%Y-%m-%d %H:%M:%S", time_struct)
    return time_string


def time_to_timestamp(dt="2023-06-01 00:00:00"):
    """固定格式时间转换为时间戳"""
    time_array = time.strptime(dt, "%Y-%m-%d %H:%M:%S")
    timestamp = time.mktime(time_array)
    return str(int(timestamp))


# ---pydantic 相关基类---


# 字段转换基类模型
class ToCamelBaseModel(BaseModel):
    """将下划线变量转为驼峰命名"""

    model_config = ConfigDict(
        from_attributes=True, #  允许从 ORM 对象转换
        populate_by_name=True, # 允许使用字段名和别名
        alias_generator=to_camel_case, # 使用别名生成器
    )
